const utils_index = require('../utils/index')
const Log = require('../models/log')

/**
 * 访问日志
 * 
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */

const log_middle_were = function(req,res,next) {
	if (req.baseUrl !== '/') {
        // console.log('req url:', req._parsedUrl.pathname)
        const request_method = req.method
        const request_url = req._parsedUrl.pathname
        const request_ip = utils_index.getClientIp(req)
        if (req.body.user_name) {
            const request_parameter = req.body
            const user_name = req.body.user_name
            Log.create({
                user_name: user_name,
                user_ip: request_ip,
                request_url: request_url,
                request_method: request_method,
                request_parameter: JSON.stringify(request_parameter)
            }).then( () => {
                next()
            })
        } else if (req.query.user_name) {
            const request_parameter = req.query
            const user_name = req.query.user_name
            Log.create({
                user_name: user_name,
                user_ip: request_ip,
                request_url: request_url,
                request_method: request_method,
                request_parameter: JSON.stringify(request_parameter)
            }).then( () => {
                next()
            })
        }
	}
	next()
}

module.exports = log_middle_were